/**
 * 时间转换 标准时间
 * @param  {[string]} dateTime [时间戳]
 * @param  {[type]} type     [需要转化的类型]
 * 0:yy-mm-dd
 * 1:yy-mm-dd h:min
 * 2:yy-mm
 * @return {[type]}          [转化后的时间]
 */


function formatNormal(dateTime, type) {
    var unixTimestamp = new Date(dateTime);
    var y = unixTimestamp.getFullYear();
    var m = unixTimestamp.getMonth() + 1;
    var d = unixTimestamp.getDate();
    var h = unixTimestamp.getHours();
    var min = unixTimestamp.getMinutes();
    if (m < 10) {
        m = "0" + m;
    }
    if (d < 10) {
        d = "0" + d;
    }
    if (h < 10) {
        h = "0" + h;
    }
    if (min < 10) {
        min = "0" + min;
    }

    var time0 = y + "-" + m + "-" + d;
    var time1 = y + "-" + m + "-" + d + " " + h + ":" + min;
    var time2 = y + "-" + m;


    if (type == 0) {
        return time0;
    }
    if (type == 1) {
        return time1;
    }
    if (type == 2) {
        return time2;
    }
}
/**
 *  将对象转化为url参数格式 ，方便axios post请求
 * @param data
 * @returns {string}
 */
function formartPostParms(data) {
    var d = '';
    if (data instanceof Object) {
        for (var x in data) {
            if (data[x] === '') {
                continue;
            }
            d += '&' + x + '=' + data[x];
        }
    }
    return d.substr(1);
}

/**
 * 判断是否登录，是返回user信息，否则跳转登录
 */
var userLogin = {
    //通过 user 判断用户是否登录
    info: function() {
        var user = JSON.parse(sessionStorage.getItem('user'));
        return user;
    },
    //判断用户登录是否登录
    ifLogin: function() {
        var flag = true;
        if (this.info()) {
            axios({
                url: urlParam.domain() + "/api/tokenVerify",
                method: 'post',
                params: {
                    token: urlParam.token(),
                }
            }).then(result => {
                if (!result.data.data) {
                    flag = userLogin.clearLogin();
                }
            })
        } else {
            alert("请先登录");
            sessionStorage.setItem("beforeUrl", window.document.location.href);
            window.location.href = '../../html/login/login.html';
            flag = false;
        }
        return flag;
    },
    //清空失效用户登录信息
    clearLogin: function() {
        sessionStorage.clear();
        sessionStorage.setItem("beforeUrl", window.document.location.href);
        window.location.href = '../../html/login/login.html';
        return false;
    },
    //用户信息
    userInfo: function() {
        if (this.ifLogin()) {
            if (!globalAPI.readCookie(urlParam.token())) {
                axios({
                    url: urlParam.domain() + "/api/user/getUser",
                    method: 'get',
                    params: {
                        token: urlParam.token()
                    }
                }).then(result => {
                    globalAPI.setCookie(urlParam.token(), JSON.stringify(result.data.data), 1);
                });
            }
            return JSON.parse(globalAPI.readCookie(urlParam.token()));
        }
    },
    //重新加载用户信息
    reLoadUserInfo: function() {
        globalAPI.setCookie(urlParam.token(), '', -1);
        return this.userInfo();
    }
}



// 加减器组件
let counter = {
    template: `<div class="counter">
    <span class="reduce" @click="reduce()">-</span>
    <input class="input" @blur="changeNum()" type="text" v-model="val" pattern="[0-9]*">
    <span class="add" @click="add()">+</span>
    </div>`,
    props: ["buynum", "spix", "pdix"],
    data() {
        return {
            val: this.buynum,
            sIndex: this.spix,
            pIndex: this.pdix

        }
    },
    methods: {
        changeNum: function() {
            if (this.val > 1) {
                this.$emit('callback', this.val, this.sIndex, this.pIndex)
            } else {
                this.val = 1;
                this.$emit('callback', this.val, this.sIndex, this.pIndex)
            }
        },

        reduce: function() {
            if (this.val > 1) {
                this.val--;
                this.$emit('callback', this.val, this.sIndex, this.pIndex)
            } else {
                this.val = 1;
                this.$emit('callback', this.val, this.sIndex, this.pIndex)
            }
        },
        add: function() {
            this.val++;
            this.$emit('callback', this.val, this.sIndex, this.pIndex)
        },

    },
    watch: {
        // 保存购物车数量
        val: function() {
            sessionStorage.setItem("cartCount", this.val)
        }
    }

}

window.onload = function() {
    //提示用户浏览器版本过低跟换升级浏览器
    document.getElementsByTagName("body")[0].insertAdjacentHTML("beforeend", `
    <!--[if lt IE 9]>
    <div style="position:absoulute;left:0;top:0;width:100%;height:50px;background:rgb(230,104,27);color:rgb(255,255,255);border-bottom:1px solid rgb(230,230,198);text-align:center;line-height:50px;font-size:12px;">
    您使用的浏览器版本过低，可能会影响到您浏览本网页，建议您升级您的浏览器。如果您切换到了兼容模式，建议更改为极速模式浏览！
    </div>
    <![endif]-->
    `);
}

//将剩余秒数转换为天 时 分 秒格式
function transformTimeleft(time) {
    let obj = {};
    obj.second = time % 60;
    obj.minute = parseInt(time / 60 % 60);
    obj.hour = parseInt(time / 3600 % 24);
    obj.day = parseInt(time / 86400);
    return obj;
}

//全局方法
var globalAPI = {};
//设置cookie hours是过期时间 现在后台维持登录是5个小时
/*
删除cookie
    globalAPI.setCookie(key, "", -1);
*/
globalAPI.setCookie = function(key, value, hours) {
    var expire = "";
    if (hours != null) {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = key + "=" + escape(value) + expire + ";path=/"; //全域名下可用
};
//globalAPI.writeCookie("myCookie", "myname", 5);
//读取cookie
globalAPI.readCookie = function(key) {
    var cookieValue = "";
    var search = key + "=";
    if (document.cookie.length > 0) {
        var offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            var end = document.cookie.indexOf(";", offset);
            if (end == -1)
                end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
};

//时间戳转日期
/*
globalAPI.getDate({n:6156161651,format:"YYYY-MM-DD hh:mm:ss"})
globalAPI.getDate({
    n:1635161616, //n为时间戳，如果没有返回当前日期
    format:"YYYY-MM-DD hh:mm:ss" //format为返回的日期格式，其中英文将会被替换成对应日期的数字，注意大小写 如果没有参数返回的日期格式为 2017-12-15
})
*/
globalAPI.getDate = function(josn) {
    if (!josn) {
        var josn = {};
    }
    if (josn.n) {
        var nowdate = new Date(josn.n);
    } else {
        var nowdate = new Date();
    }
    var nowyear = nowdate.getFullYear(); //年
    var nowmonth = nowdate.getMonth() + 1; //月
    (nowmonth < 10) && (nowmonth = "0" + nowmonth);
    var nowri = nowdate.getDate(); //日
    (nowri < 10) && (nowri = "0" + nowri);
    if (!josn.format) {
        return nowyear + "-" + nowmonth + "-" + nowri;
    }
    var nowhour = nowdate.getHours(); //小时
    (nowhour < 10) && (nowhour = "0" + nowhour);
    var nowmin = nowdate.getMinutes(); //分钟
    (nowmin < 10) && (nowmin = "0" + nowmin);
    var nowsecond = nowdate.getSeconds(); //秒
    (nowsecond < 10) && (nowsecond = "0" + nowsecond);
    return josn.format.replace(/YYYY/, nowyear).replace(/MM/, nowmonth).replace(/DD/, nowri).replace(/hh/, nowhour).replace(/mm/, nowmin).replace(/ss/, nowsecond);
}

//验证图片类型
//参数为字符串 文件后缀
globalAPI.testImgType = function(str) {
    var str = str.toLowerCase(); //文件后缀可能为大写，这里转为小写
    var type = { //合格的 图片格式
        "jpg": 1,
        "png": 1,
    }
    return !!(type[str]); //返回布尔值
}

//console.log(globalAPI.readCookie("myCookie"));

//获得总页数
function getPageCount(total, pageSize) {
    if (parseInt(total) <= parseInt(pageSize)) {
        return 1;
    }
    return total % pageSize == 0 ? total / pageSize : parseInt(total / pageSize) + 1;
}

//商品详情点击购买格式化
function formatProduct(buyNumber, productId, colorName, sizeName, productNumber, name, productPrice, shopName, picImg, sellerId, type, customValues, orderType) {
    var obj = [];
    var shop = [];
    var product = {};
    product.buyNumber = buyNumber;
    product.productNumber = productNumber;
    product.productId = productId;
    product.name = name;
    product.picImg = picImg;
    product.productPrice = productPrice;
    product.productAmount = buyNumber * productPrice;
    product.shopName = shopName;
    product.colorName = colorName;
    product.sizeName = sizeName;
    product.sellerId = sellerId;
    product.type = type || 0;
    product.customValues = customValues || null;
    product.orderType = orderType || 0;
    shop.push(product);
    obj.push(shop);
    sessionStorage.setItem("selectProduct", JSON.stringify(obj));
    window.location.href = "../../html/cart/cart_confirm.html";
}

/**
 * 会员退出
 */
function loginOut() {
    /*sessionStorage.removeItem("user");
    sessionStorage.removeItem("loginName");
    window.location.href = '../login/login.html';*/
    axios({
        method: 'post',
        url: urlParam.domain() + '/api/keepActive',
        responseType: 'stream'
    }).then(function(r) {
        if (r.data.code == 1) {
            sessionStorage.clear();
            sessionStorage.setItem("beforeUrl", window.document.location.href)
            window.location.href = '../../html/login/login.html';
        } else {
            alert(r.data.message);
        }
    });
}